package net.tavion.demo.chapter1;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServer {

    static Logger logger=LoggerFactory.getLogger(NettyServer.class);

    private final Integer port=9088;

    EventLoopGroup workerGroup = null;
    EventLoopGroup bossGroup = null;
    ServerBootstrap bootstrap = null;

    public void start() throws Exception {
        try {
            workerGroup = new NioEventLoopGroup();
            bossGroup = new NioEventLoopGroup();
            bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port).childHandler(
                    new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    }
            );

            ChannelFuture f = bootstrap.bind().sync();
            logger.info("server {} running on port {}",NettyServer.class.getName(),port);

            f.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }
    }

}
